<?php

class UserController extends CController {
    const PAGE_SIZE=25;

    /**
     * @var string specifies the default action to be 'list'.
     */
    public $defaultAction='list';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',
                  'actions'=>array('captcha', 'signup', 'preview', 'done'),
                  'users'=>array('?')
            ),
            array('allow', 
                  'actions'=>array('list','show', 'forgetpassword'),
                  'users'=>array('*')
            ),
            array('allow', // can update only own profile
                  'actions'=>array('editprofile', 'delete'),
                  'roles'=>array('updateProfile', 'admin')
            ),
            array('allow', // allow admin user to perform 'admin' action
                  'actions'=>array('admin'),
                  'roles'=>array('admin')
            ),
            array('deny',  // deny all users
                'users'=>array('*')
            )
        );
    }

    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image
            // this is used by the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xF5F5F5,
            ),
        );
    }

    /**
     * Shows a particular model.
     */
    public function actionShow() {
        $this->render('show',array('model'=>$this->loadUser()));
    }

    public function actionSignup() {
        $model=new SignupForm();
        if(isset($_POST['SignupForm'])) {
            $model->attributes=$_POST['SignupForm'];
            if($model->save())
                $this->redirect(array('preview'));
        }
        elseif(isset(Yii::app()->session['SignupForm'])){
            $model->attributes=Yii::app()->session['SignupForm'];
            $model->password = '';
            $model->cpassword = '';
        }
        $this->render('signup',array('model'=>$model));
    }

    public function actionPreview(){
        if(isset(Yii::app()->session['SignupForm'])){
            $model = new SignupForm();
            $model->attributes = Yii::app()->session['SignupForm'];
            $this->render('preview', array('model'=>$model));
        }
        else{
            $this->redirect(array('signup'));
        }
    }

    public function actionDone(){
        if(isset(Yii::app()->session['SignupForm'])){
            $user = new User();
            $attributes = Yii::app()->session['SignupForm'];
            if(strlen($attributes['home_page_url'])==0) unset($attributes['home_page_url']);
            $user->attributes = $attributes;

            //!PENDING: изменить форму для ввода дополнительных данных
            $user->birthdate = 0;
            $user->timezone_ofs = 0;
            $user->language_id = 1;
            $user->gender = 'm';
            
            if($user->save()){
                //unset(Yii::app()->session['SignupForm']);
                $this->render('done', array('error'=>$this->sendVerificationEmail($user)));
            }
            else{
                $this->render('creation_error');
            }
        }
        else{
            $model = new SignupForm();
            $this->redirect(array('signup'));
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'show' page.
     */
    public function actionEditprofile() {
        $model=$this->loadUser();
        if(isset($_POST['User'])) {
            $model->attributes=$_POST['User'];
            if($model->save())
                $this->redirect(array('show','id'=>$model->id));
        }
        $this->render('editprofile',array('model'=>$model));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'list' page.
     */
    public function actionDelete() {
        if(Yii::app()->request->isPostRequest) {
        // we only allow deletion via POST request
            $this->loadUser()->delete();
            $this->redirect(array('list'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionList() {
        $criteria=new CDbCriteria;

        $pages=new CPagination(User::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $models=User::model()->findAll($criteria);

        $this->render('list',array(
            'models'=>$models,
            'pages'=>$pages,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $this->processAdminCommand();

        $criteria=new CDbCriteria;

        $pages=new CPagination(User::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort=new CSort('User');
        $sort->applyOrder($criteria);

        $models=User::model()->findAll($criteria);

        $this->render('admin',array(
            'models'=>$models,
            'pages'=>$pages,
            'sort'=>$sort,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadUser($id=null) {
        if($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=User::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand() {
        if(isset($_POST['command'], $_POST['id'])) {
            switch($_POST['command']){
                case 'fulldelete':
                    $this->loadUser($_POST['id'])->delete();
                    $this->refresh();
                    break;
                case 'delete':
                    $this->loadUser($_POST['id'])->markAsDeleted();
                    $this->refresh();
                    break;
                case 'restore':
                    $this->loadUser($_POST['id'])->markAsNormal();
                    $this->refresh();
                    break;
                case 'block':
                    $this->loadUser($_POST['id'])->markAsBlocked();
                    $this->refresh();
                    break;
            }
        }
    }

    public function actionForgetpassword(){
        $this->render('forgetpassword');
    }

    /**
     * @return array attributes that can be massively assigned
     */
    public function safeAttributes() {
        return array(
            'email',
            'password',
            'first_name',
            'last_name',
            'nickname',
            'home_page_url',
            'short_description',
        );
    }

    /**
     * Send verification letter to user email
     * @param string $signature md5 checksum
     * @return boolean
     */
    private function sendVerificationEmail($user){
        $mailer = Yii::app()->mailer;
        $msg = $mailer->newMessage()
            ->setSubject(Yii::app()->name.': Verification letter')
            ->setTo(array($user->email => $user->nickname));
        $mailer->getView('verification_email', $user->getAttributes());
        return $mailer->send();
    }
}
